package cn.fl.risk.util;

import java.io.IOException;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import cn.cmm.base.framework.utils.BaseLogUtils;


public class SpringWebSocketHandler extends TextWebSocketHandler {
    private static final ArrayList<WebSocketSession> users;//这个会出现性能问题，最好用Map来存储，key用userid
    private static final Logger logger = LoggerFactory.getLogger(SpringWebSocketHandler.class);
    static {
        users = new ArrayList<WebSocketSession>();
    }
    
    public SpringWebSocketHandler() {
        // TODO Auto-generated constructor stub
    }

    /**
     * 连接成功时候，会触发页面上onopen方法
     */
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // TODO Auto-generated method stub
        //System.out.println("connect to the websocket success......当前数量:"+users.size());
        BaseLogUtils.info(logger, "afterConnectionEstablished", "connect to the websocket success......当前数量:"+users.size());
        users.add(session);
        logger.debug("websocket用户"+session.getAttributes().get("WEBSOCKET_USERNAME")+"登录成功");
        for (WebSocketSession user : users) {
        	Object o =user.getAttributes().get("WEBSOCKET_USERNAME");
        	String username=o.toString();
        	boolean b = user.isOpen();
        	logger.debug( "websocket用户"+username+"isopen"+b);
        }
        //这块会实现自己业务，比如，当用户登录后，会把离线消息推送给用户
        //TextMessage returnMessage = new TextMessage("你将收到的离线");
        //session.sendMessage(returnMessage);
    }
    
    /**
     * 关闭连接时触发
     */
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.debug("websocket connection closed......");
        String username= (String) session.getAttributes().get("WEBSOCKET_USERNAME");
        //System.out.println("用户"+username+"已退出！");
        BaseLogUtils.info(logger, "afterConnectionEstablished", "用户"+username+"已退出！退出前用户数："+users.size());
        logger.debug("websocket用户"+session.getAttributes().get("WEBSOCKET_USERNAME")+"退出");
        users.remove(session);
        logger.debug("websocket用户剩余在线用户"+users.size());
        //System.out.println("剩余在线用户"+users.size());
    }

    /**
     * js调用websocket.send时候，会调用该方法
     */
    @Override    
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }

    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){session.close();}
        logger.debug("websocket connection closed......");
        users.remove(session);
    }

    public boolean supportsPartialMessages() {
        return false;
    }
    
    
    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
    	BaseLogUtils.info(logger, "sendMessageToUser", "进入websocat发送消息 userName="+userName);
        for (WebSocketSession user : users) {
        	logger.debug( "websocket用户"+user.getAttributes().get("WEBSOCKET_USERNAME")+"isopen"+user.isOpen());
            if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) {
                try {
                    if (user.isOpen()) {
                    	BaseLogUtils.info(logger, "sendMessageToUser", "WEBSOCKET_USERNAME"+user.getAttributes().get("WEBSOCKET_USERNAME"));
                        user.sendMessage(message);
                        logger.debug( "websocket用户"+user.getAttributes().get("WEBSOCKET_USERNAME")+"sendMessage成功");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    
    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            try {
                if (user.isOpen()) {
                    user.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
